package leetcode.code704.BinarySearch;

public class Solution1 implements IBinarySearch {

	public static void main(String[] args) {
		int[] nums = { -1, 0, 3, 5, 9, 12 };
		int target = 9;
		myPrint(nums, target, new Solution1());

		int[] nums1 = { -1, 0, 3, 5, 9, 12 };
		int target1 = 2;
		myPrint(nums1, target1, new Solution1());

		int[] nums2 = { 2, 5 };
		int target2 = 5;
		myPrint(nums2, target2, new Solution1());
	}

	public static void myPrint(int[] nums, int target, IBinarySearch ibs) {
		int result = ibs.search(nums, target);
		System.out.println(result);
	}

//	输入: nums = [-1,0,3,5,9,12], target = 9
//	输出: 4
//	解释: 9 出现在 nums 中并且下标为 4

//	输入: nums = [-1,0,3,5,9,12], target = 2
//	输出: -1
//	解释: 2 不存在 nums 中因此返回 -1

	@Override
	public int search(int[] nums, int target) {
		int len = nums.length;
		if (len == 1)
			return nums[0] == target ? 0 : -1;
		int left = 0;
		int right = len - 1;
		int midle = 0;
		int midleNum = 0;
		while (left <= right) { // 等号
			midle = (right + left) / 2;
			midleNum = nums[midle];
			if (midleNum == target) {
				return midle;
			} else if (midleNum > target) {// && midle != right
				right = midle - 1; // -1 不做不行的
			} else if (midleNum < target) {// && midle != left
				left = midle + 1; // +1
			} else {
				return -1;
			}
		}
		return -1;
	}

}
